package com.qdxwx.web.controller.teacher;

import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.entity.Ztree;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.upload.UploadState;
import com.qdxwx.common.upload.UploadUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.teacher.TeacherApplyService;
import com.qdxwx.data.service.teacher.TeacherService;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.teacher.TeacherApply;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Teacher 教师入驻
 */
@Controller
@RequestMapping("/teacher")
public class TeacherApplyController extends BaseController {

    @Autowired
    private TeacherApplyService teacherApplyService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/join.html")
    public String demo(ModelMap mmap) {
        List<Ztree> ztreeSubject = categoryService.getTree(0);
        mmap.put("ztreeSubject", ztreeSubject);
        return getViewPath("teacher/teacher-join");
    }

    @RequestMapping("/join.json")
    @ResponseBody
    public AjaxResult add(HttpServletRequest request) {
        String name = request.getParameter("name");
        if (TKString.isEmpty(name)) return AjaxResult.error("请输入名称");
        String mobile = request.getParameter("mobile");
        if (!TKString.isMobile(mobile)) return AjaxResult.error("请输入正确的手机号码");
        if (teacherService.checkMobile(mobile)) return AjaxResult.error("该手机号已被注册");
        String avatar = request.getParameter("avatar");
        if (TKString.isEmpty(avatar)) return AjaxResult.error("请输入上传头像");
        String intro = request.getParameter("intro");
        if (TKString.isEmpty(intro)) return AjaxResult.error("请输入您的个人简介");
        String finalSchool = request.getParameter("finalSchool");
        if (TKString.isEmpty(finalSchool)) return AjaxResult.error("请输入您的毕业学校");
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        if (channelId < 1) return AjaxResult.error("请输入您的专业");
        String title = request.getParameter("title");
        if (TKString.isEmpty(title)) return AjaxResult.error("请输入您的头像");
        String education = request.getParameter("education");
        if (TKString.isEmpty(education)) return AjaxResult.error("请输入教师资历说明");
        TeacherApply teacherApply = new TeacherApply();
        teacherApply.setStatus(0);
        teacherApply.setMobile(mobile);
        if (teacherApplyService.count(teacherApply) > 0) {
            return AjaxResult.error("此号码已提交过申请，请耐心等待审核结果");
        }
        teacherApply.setCompanyId(LoginUser.getCompanyId(request));
        teacherApply.setName(name);
        teacherApply.setAvatar(avatar);
        teacherApply.setIntro(intro);
        teacherApply.setFinalSchool(finalSchool);
        teacherApply.setSubjectId(channelId);
        teacherApply.setTitle(title);
        teacherApply.setTeachYear(TKConvert.toInteger(request.getParameter("teachYear")));
        teacherApply.setEducation(education);
        int row = teacherApplyService.insert(teacherApply);
        return row > 0 ? AjaxResult.success() : AjaxResult.error("提交失败，请稍后再试");
    }

    //验证手机号码是否已经被注册
    @RequestMapping("/check.json")
    @ResponseBody
    public AjaxResult teacherCooperCheck(HttpServletRequest request) {
        String mobile = request.getParameter("mobile");
        if (!TKString.isMobile(mobile)) return AjaxResult.error("请输入正确的手机号码");
        if (teacherService.checkMobile(mobile)) return AjaxResult.error("该手机号已被注册");
        TeacherApply teacherApply = new TeacherApply();
        teacherApply.setStatus(0);
        teacherApply.setMobile(mobile);
        if (teacherApplyService.count(teacherApply) > 0) return AjaxResult.error("此号码已提交过申请，请耐心等待审核结果");
        return AjaxResult.success("手机号可用");
    }

    /**
     * 图片上传文件
     */
    @PostMapping("/upload.json")
    @ResponseBody
    public AjaxResult upload(MultipartFile file) {
        if (file.isEmpty()) return AjaxResult.error("请选择文件图片");
        //这里要改，先缓存到临时文件夹，保存时再转到正式文件夹，否则很多垃圾
        UploadState uploadState = UploadUtils.saveImageFile(file, UploadConfig.uploadTempFolder);
        if (uploadState.getCode() == 0) {
            return AjaxResult.success(uploadState.getSavePath());
        } else {
            return AjaxResult.error(uploadState.getMsg());
        }
    }

    /**
     * 获取树形菜单json数据
     */
    @RequestMapping(value = "/ztree.json", method = RequestMethod.GET)
    @ResponseBody
    public List<HashMap<String, Object>> Ztree() {
        List<Category> list = categoryService.getList(new Category());
        List<HashMap<String, Object>> result = new ArrayList<>();
        return Splicing(list, result);
    }

    /**
     * 拼接树形菜单所需要的json格式
     */
    private List<HashMap<String, Object>> Splicing(List<Category> categories, List<HashMap<String, Object>> result) {
        for (Category category : categories) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", category.getCategoryId());
            map.put("name", category.getCategoryName());
            map.put("open", true);      //设置是否展开
            List<HashMap<String, Object>> result1 = new ArrayList<>();
            List<Category> children = categoryService.getChildren(category.getCategoryId());   //下级菜单
            map.put("children", Splicing(children, result1));
            result.add(map);
        }
        return result;
    }
}
